package com.centriole.common.utils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;

/**
 * @Author: zhangjj
 * @Description:
 * @Date: Created in 2018/4/24 0024 13:56
 * @Modified:
 */
public class EntityUtil {
    public static void main(String[] args) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("ip", "192.168.1.17");
//        map.put("port", "7077");
//        map.put("uri", "ki");
//        map.put("pushType", "2");
//        map.put("requestTimeOut", "3");
//        map.put("pushTime", new Date());
//
//
//        MessageParamEntity mpe = (MessageParamEntity) EntityUtil.getEntityByMap(new MessageParamEntity(), map);
//
//        System.out.println(mpe.toString());
    }

    /**
     * @Author: zhangjj
     * @Description: map to 实体类
     * @Date: 15:53 2018/5/10 0010
     * @Modified:
     * @Param: map 需要转换的 map 数据
     * @Param: object 目标实体类
     * @Return: object
     */
    public static Object getEntityByMap(Object object, Map<String, Object> map) {
        Field[] field = object.getClass().getDeclaredFields();

        int fieCount = field.length;

        String objectName = "";
        String[] objectType = new String[fieCount];

        for (int i = 0; i < fieCount; i++) {
            objectName = field[i].getName();
            objectType[i] = field[i].getGenericType().toString();

            try {
                field[i].setAccessible(true);

                if (objectType[i].equals(String.class.toString())) {
                    field[i].set(object, map.get(objectName).toString());
                }
                if (objectType[i].equals(Integer.class.toString()) || objectType[i].equals(int.class.toString())) {
                    field[i].set(object, Integer.parseInt(map.get(objectName).toString()));
                }
                if (objectType[i].equals(Character.class.toString()) || objectType[i].equals(char.class.toString())) {
                    field[i].set(object, map.get(objectName).toString().toCharArray()[0]);
                }
                if (objectType[i].equals(Date.class.toString())) {
                    field[i].set(object, map.get(objectName));
                }
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
            } catch (NullPointerException npe) {
//                try {
//                    field[i].set(object, "");
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }
            }
        }

        return object;
    }
}
